import subprocess
import os
import shutil
import sys
import glob

__author__ = 'Administrator'

PATH_SEP = os.sep
DEFAULT_TOMCAT_PROJECT_LIST = ["docs", "examples", "host-manager", "manager", "ROOT"]

PATH_TOMCAT = os.path.join("e:", os.sep, "box", "apache-tomcat-6.0.43")
PATH_WORK = os.path.join("e:", os.sep, "box", "svn")

PROJECT_LIST = ["vcp", "proj"]


def clean(path_tomcat):
    webapps_path = os.path.join(path_tomcat, "webapps")
    dirs = os.listdir(webapps_path)
    for d in dirs:
        if d not in DEFAULT_TOMCAT_PROJECT_LIST:
            del_file_or_folder(os.path.join(webapps_path, d))

    work_path = os.path.join(path_tomcat, "work")
    dirs = os.listdir(work_path)
    for d in dirs:
        del_file_or_folder(os.path.join(work_path, d))


def build(path_svn):
    os.chdir(path_svn)
    os.system("ant")


def svnUpdate(path_svn):
    os.chdir(path_svn)
    subprocess.call(["svn", "up"])


def tomcat_start(path_tomcat):
    os.chdir(os.path.join(path_tomcat, "bin"))
    subprocess.call([os.path.join(path_tomcat, "bin", "startup.bat")])


def tomcat_stop(path_tomcat):
    os.chdir(os.path.join(path_tomcat, "bin"))
    subprocess.call([os.path.join(path_tomcat, "bin", "shutdown.bat")])


def del_file_or_folder(directory):
    if os.path.exists(directory):
        try:
            if os.path.isdir(directory):
                # delete folder
                shutil.rmtree(directory)
            else:
                # delete file
                os.remove(directory)
        except:
            print("exception ", sys.exc_info()[0])
            raise
    else:
        print("not found", directory)


def do_job():
    for project in PROJECT_LIST:
        project_war_path = os.path.join(PATH_WORK, project)
        svnUpdate(project_war_path)
        build(project_war_path)

    tomcat_stop(PATH_TOMCAT)
    clean(PATH_TOMCAT)

    for project in PROJECT_LIST:
        os.chdir(os.path.join(PATH_WORK, project))
        for file in glob.glob("*.war"):
            shutil.copy(file, os.path.join(PATH_TOMCAT, "webapps"))

    tomcat_start(PATH_TOMCAT)


def main():
    do_job()


if __name__ == "__main__":
    main()
